package com.motu.monstercity.server.game.web;

import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.commondata.bag.Item;
import com.motu.monstercity.server.game.commondata.bag.ReviewItem;
import com.motu.monstercity.server.game.commondata.build.BuildConstant;
import com.motu.monstercity.server.game.commondata.build.BuildMain;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.partner.PartnerConstant;
import com.motu.monstercity.server.game.commondata.partner.PartnerMain;
import com.motu.monstercity.server.game.commondata.partner.WeaponMain;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryMain;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.logic.*;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.base.ServerConfig;
import com.motu.vertx.module.utility.mysql.MysqlClient;
import com.motu.vertx.module.utility.mysql.MysqlTool;
import com.motu.vertx.module.utility.toolset.*;
import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.sync.Sync;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.UUID;

public class WebGMManager {
    private static final String CMD_GM_ONEKEY_ALL_ITEM = "gm.okitem"; //一键获得所有道具
    private static final String CMD_GM_ONEKEY_LEVEL_MAX = "gm.okall"; //一键最强
    private static final String CMD_GM_UPDATE_ACT_WORD = "gm.updateactword"; // act_word配置更新
    private static final String CMD_GM_ADD_ITEM = "gm.additem"; //发放道具
    private static final String CMD_GM_BANNED_USER = "gm.banneduser"; //封号并踢下线
    private static final String CMD_GM_UNBANNED = "gm.unbanned"; //解封
    private static final String CMD_GM_SET_ROLE = "gm.setrole"; // 设置初级账号，设置中级账号，设置高级账号
    private static final String CMD_GM_SEND_MAIL = "gm.sendmail"; //群发邮件
    private static final String CMD_GM_BANNED_CHAT = "gm.bannedchat"; //给用户禁言
    private static final String CMD_GM_CHANGE_NAME = "gm.changename"; // 角色改名


    private final static Logger logger = LoggerFactory.getLogger(WebGMManager.class);

    public static void handleMessage(JsonObject message, Handler<AsyncResult<JsonObject>> handler) {
        JsonObject data = message;
        logger.info("WebGMManager.handleMessage data:" + data);
        String cmd = data.getString("cmd");
        String reason = data.getString("reason");
        String adminName = data.getString("adminName");
        JsonObject params = data.getJsonObject("params");

        JsonObject jsonObject = new JsonObject();
        switch (cmd) {
            case CMD_GM_UPDATE_ACT_WORD:// act_word配置更新
                jsonObject = handleUpdateActWord( adminName, reason, params, cmd);
                break;
            case CMD_GM_UNBANNED:// 解封
                jsonObject = handleUnBannedUser( adminName, reason, params, cmd);
                break;
            case CMD_GM_SEND_MAIL:// 发邮件
                jsonObject = handleSendMail( adminName, reason, params, cmd);
                break;
            case CMD_GM_BANNED_CHAT:// 给用户禁言
                jsonObject = handleBannedChat( adminName, reason, params, cmd);
                break;
            case CMD_GM_CHANGE_NAME:// 角色改名
                jsonObject = handleChangeName( adminName, reason, params, cmd);
                break;
            default:
                UserInfo userInfo = null;
                if (params.containsKey("uid")) {
                    long userId = Long.parseLong(params.getString("uid"));
                    userInfo = GameUser.getUserInfo(userId);
                }
                if (userInfo == null)  {
                    jsonObject = sendResponse(cmd, ErrorWord.ITEM_NOT_EXIST);
                } else {
                    switch (cmd) {
                        case CMD_GM_ONEKEY_ALL_ITEM://一键获得所有道具,建筑和干员
                            if (!ServerConfig.isOnlineServer()) {// 非正式服才允许执行
                                jsonObject = handleOneKeyItem(userInfo, userInfo.getId(), adminName, reason, params, cmd);
                            } else{
                                jsonObject = sendResponse(cmd, ErrorWord.PERMISSION_DENIED);
                            }
                            break;
                        case CMD_GM_ONEKEY_LEVEL_MAX:// 一键最强
                            if (!ServerConfig.isOnlineServer()) {// 非正式服才允许执行
                                jsonObject = handleOneKeyLevelMax(userInfo, userInfo.getId(), adminName, reason, params, cmd);
                            } else{
                                jsonObject = sendResponse(cmd, ErrorWord.PERMISSION_DENIED);
                            }
                            break;
                        case CMD_GM_SET_ROLE:// 设置初级账号，设置中级账号，设置高级账号
                            if (!ServerConfig.isOnlineServer()) {// 非正式服才允许执行
                                jsonObject = handleSetRole(userInfo, userInfo.getId(), adminName, reason, params, cmd);
                            } else{
                                jsonObject = sendResponse(cmd, ErrorWord.PERMISSION_DENIED);
                            }
                            break;
                        case CMD_GM_ADD_ITEM:// 发放道具
                            jsonObject = handleAddItem(userInfo, userInfo.getId(), adminName, reason, params, cmd);
                            break;
                        case CMD_GM_BANNED_USER:// 封号并踢下线
                            jsonObject = handleBannedUserUser(userInfo, userInfo.getId(), adminName, reason, params, cmd);
                            break;

                    }
                }
                break;
        }
        handler.handle(Future.succeededFuture(jsonObject));
    }

    // 设置初级账号，设置中级账号，设置高级账号
    private static JsonObject handleSetRole(UserInfo userInfo, long userId, String adminName, String reason, JsonObject params, String cmd) {
        // 获取参数
        if (!params.containsKey("type")) {
            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        int type = params.getInteger("type");
        int level = 0;
        byte vip = 8;
        int repu = 0;
        int mapId = 0;
        int areaId = 0;
        int partnerLevel = 0;
        int partnerLevelMax = 0;
        int weaponLevel = 0;
        int peasonNum = 100;// 初始人口都是100个
        if (type == 1) {// 初级账号
            level = 10;
            repu = 1050;
            mapId = 31;
            areaId = 13;
            partnerLevel = 50;
            partnerLevelMax = 100;
            weaponLevel = 50;
        } else if (type == 2) {// 中级账号
            level = 40;
            repu = 450000;
            mapId = 1801;
            areaId = 42;
            partnerLevel = 150;
            partnerLevelMax = 200;
            weaponLevel = 120;
        } else if (type == 3) {// 高级账号
            level = 69;
            repu = 33500000;
            mapId = 1801;
            areaId = 42;
            partnerLevel = 240;
            partnerLevelMax = 300;
            weaponLevel = 200;
        }
        if (type == 1 || type == 2 || type == 3) {
            setUserLevelVip(userInfo, userId, level, vip, repu);
            setUserStage(userInfo, userId, mapId, areaId);
            setUserTeach(userInfo, userId);
            setUserPartner(userInfo, userId, partnerLevel, partnerLevelMax);
            setUserSecr(userInfo, userId);
            setUserWeapon(userInfo, userId, weaponLevel);
            setUserItem(userInfo, userId);// 给初级账号，中级账号，高级账号，添加道具
            setUserCityInfo(userInfo, userId, peasonNum);
            FightManager.unlockMonsterTide(userId);
        }

        logger.info("###handleSetRole finish userid = " + userId + " type = " + type);
        // 返回客户端数据
        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    // //一键获得所有道具,建筑和干员
    private static JsonObject handleOneKeyItem(UserInfo userInfo, long userId, String adminName, String reason, JsonObject params, String cmd) {
        // 1、市政中心等级（玩家等级）提升至70级
        userInfo.putDiamond(100000);
        long tt = 100L;
        tt = 100 * 10000 * 10000;
        userInfo.putGold(tt);
        userInfo.update();

        // 解锁所有商业建筑
        for (BuildMain buildMain : BuildManager.getBuildMainMap().values()) {
            if (buildMain.isBusinessBuild() && buildMain.getUnlockType() == 0) {
                int isUnlock = 1;
                UserBuild userBuild = new UserBuild(userId, buildMain.getBuildId(), 1, isUnlock);//
                userBuild.putSeatNum(5);// 解锁5个委派槽位
                userBuild.doCreate();
            }
        }
        logger.info("###handleOneKeyItem add build finish!!!");


        // 获得所有干员
        for (PartnerMain partnerMain : PartnerManager.getPartnerMainMap().values()) {
            RewardManager.addReward(userInfo, partnerMain.getPartnerId(), 1, null, LogType.GM_SEND);
        }
        logger.info("###handleOneKeyItem add partner finish!!!");

        // 获得所有秘书
        for (SecretaryMain secretaryMain : SecretaryManager.getSecretaryMainMap().values()) {
            RewardManager.addReward(userInfo, secretaryMain.getSecretaryId(), 1, null, LogType.GM_SEND);
        }
        logger.info("###handleOneKeyItem add secretary finish!!!");

        // 每种武器获得20把
        for (WeaponMain weaponMain : PartnerManager.getWeaponMainMap().values()) {
            RewardManager.addReward(userInfo, weaponMain.getWeaponId(), 20, null, LogType.GM_SEND);
        }
        logger.info("###handleOneKeyItem add weapon finish!!!");

        // 所有道具获得999
        for (Item item : BagManager.getItemMap().values()) {
            if (item.getId() >= 110000) {
                RewardManager.addReward(userInfo, item.getId(), 999, null, LogType.GM_SEND);
            }
        }
        logger.info("###handleOneKeyItem add item finish!!!");

        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    // //一键最强
    private static JsonObject handleOneKeyLevelMax(UserInfo userInfo, long userId, String adminName, String reason, JsonObject params, String cmd) {
        // 1、市政中心等级（玩家等级）提升至70级
        userInfo.putLevel(70);
        userInfo.update();

        for (UserBuild userBuild : BuildManager.getUserBuildList(userId)) {
            BuildMain buildMain = BuildManager.getBuildMain(userBuild.getBuildId());
            if (buildMain.isCityCenter()) {
                userBuild.putLevel(70);
            } else if (buildMain.isBuildBank()){
                userBuild.putLevel(100);
            } else {
                userBuild.putLevel(20);
            }
            if (buildMain.isBusinessBuild()) {
                userBuild.putRecruitNum(1000);// 商业建筑招募次数
            }
            userBuild.update();
        }
        logger.info("###handleOneKeyLevelMax update build finish!!!");

        for (UserPartner userPartner : PartnerManager.getUserPartnerList(userId)) {
            userPartner.putLevel(750);
            userPartner.putMaxLevel(750);
            userPartner.update();
        }
        logger.info("###handleOneKeyLevelMax update partner finish!!!");

        for (UserWeapon userWeapon : PartnerManager.getUserWeaonList(userId)) {
            userWeapon.putMaxLevel(PartnerConstant.WEAPON_INIT_MAX_LEVEL);
            userWeapon.putLevel(PartnerConstant.WEAPON_INIT_MAX_LEVEL);
            userWeapon.update();
        }
        logger.info("###handleOneKeyLevelMax update weapon finish!!!");


        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    private static JsonObject handleUpdateActWord(String adminName, String reason, JsonObject params, String cmd) {
        // 获取参数
        if (!params.containsKey("ids")) {
            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        JsonArray idAry = params.getJsonArray("ids");
        logger.info("handleUpdateActWord, id_ary={}", idAry);
        int[] ids = new int[idAry.size()];
        for (int i = 0; i < idAry.size(); i++) {
            ids[i] = idAry.getInteger(i);
        }
        // 通知游戏服更新actword
        GameDataManager.pushGameUpdateActWordByIds(ids);
        // 返回数据
        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    private static JsonObject handleAddItem(UserInfo userInfo,long userId,String adminName, String reason, JsonObject params, String cmd) {
        logger.info("handleAddItem" + " params = " + params.toString());
        // 获取参数
        if (!params.containsKey("items")) {
            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        JsonArray items = params.getJsonArray("items");
        for (int i = 0; i < items.size(); i++) {
            JsonObject obj = items.getJsonObject(i);
            int itemId = obj.getInteger("itid");// 物品的id
            long num = obj.getLong("num");// 物品的数量

            logger.info("gm add itemid = " + itemId + " num = " + num);
            Common.PBUserData.Builder pbUserData = Common.PBUserData.newBuilder();
            if (num < 0) {
                RewardManager.subReward(userInfo, new RewardItem(itemId, num), pbUserData,LogType.GM_SEND);
            } else {
                RewardManager.addReward(userInfo, new RewardItem(itemId, num), pbUserData,LogType.GM_SEND);
            }
        }
        addWebGmLog(userId, adminName, reason, "add items:" + items.toString());
        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    public static void addWebGmLog(long userId, String adminName, String reason, String operation) {
        String sql = "insert into webmanager_gameuser_log(userid,adminname,reason,operation,addtime) values(?,?,?,?," +
                "?);";
        JsonArray params = new JsonArray();
        params.add(userId);
        params.add(adminName);
        params.add(reason);
        params.add(operation);
        params.add(TimeUtils.getCurTime());
        MysqlTool.updateToDb(MysqlClient.getServerPool(), sql, params, handler -> {
            if (handler.failed()) {
                logger.error("add addWebGmLog sql:"+sql+" params :"+params+" error:" + handler.cause());
            }
        });
    }

    private static JsonObject sendResponse(String cmd, ErrorWord er) {
        JsonObject obj = new JsonObject();
        obj.put("ret", er.value);
        if (er.value != 0) {
            String errWord = ErrorWordManager.get(cmd, er, LanguageEnum.ZHS.value);
            if (errWord != null) {
                obj.put("errmsg", errWord);
            }
        }
        return obj;
    }

    /***
     * 封号并踢下线
     */
    private static JsonObject handleBannedUserUser(UserInfo userInfo,long userId,String adminName, String reason, JsonObject params, String cmd) {
        // 获取参数
        if (!params.containsKey("uid") && !params.containsKey("time") && !params.containsKey("type")) {
            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        return bannedUser(userInfo,userId,adminName, reason, params, cmd);
    }

    /***
     * 执行封号并踢下线
     */
    private static JsonObject bannedUser(UserInfo userInfo,long userId,String adminName, String reason, JsonObject params, String cmd) {
        int type = params.getInteger("type");
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null || userInfo == null) {
            return sendResponse(cmd, ErrorWord.ENTITY_NOT_EXIST);
        }
        int bantime = params.getInteger("time");


        String sql = "";
        JsonArray array = new JsonArray();

        sql = "insert into banned_user(type,account_id,platform,user_id,user_name,server_id,gm_name,reason,ban_time," +
                "add_time,device_id,ip) ";
        sql += " values(?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE ban_time=?, gm_name=?, reason=?, add_time=?;";
        array.add(type);
        array.add(userExtInfo.getAccountId());
        array.add(userExtInfo.getPlatform());
        array.add(userId);
        array.add(userInfo.getUserName());
        array.add(userInfo.getServerId());
        array.add(adminName);
        array.add(reason);
        array.add(bantime);
        array.add(TimeUtils.getCurTime());
        array.add(userExtInfo.getDeviceId());
        array.add(userExtInfo.getIp());
        array.add(bantime);
        array.add(adminName);
        array.add(reason);
        array.add(TimeUtils.getCurTime());

        String sqlStr = sql;
        Long newid = Future.await(MysqlTool.insertAndGetID(MysqlClient.getServerPool(), sqlStr, array));
        if (newid > 0) {
            addWebGmLog(userId, adminName, reason, "seal user time:" + TimeUtils.getTimeStr(bantime) + " type:" + type);
            // 把用户踢下线
            GameUser.kickUser(userId, ErrorWord.BANNED_ACCOUNT);
            //封角色-特殊处理
            if(type == 0) {
                userExtInfo.putBannedTime(bantime);
                userExtInfo.updateQueueNow();
//                BanManager.doBan(userId);//目前暂不需要封号处理其他模块数据
            }
            // 数数用户封禁事件
//            ThinkingDataManager.pushUserBanData(userId, 1);
            // 返回客户端信息
            return sendResponse(cmd, ErrorWord.SUCCESS);
        } else {
            logger.info("handleSealUser fail userid = " + userId);
            return sendResponse(cmd, ErrorWord.MYSQL_INSERT_FAILED);
        }
    }

    /***
     * 解封
     */
    private static JsonObject handleUnBannedUser(String adminName, String reason, JsonObject params, String cmd) {
        // 获取参数
        if (!params.containsKey("type") ) {
            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        int type = params.getInteger("type");
        String whereSql = " type = ?";
        JsonArray sqlParams = new JsonArray();
        long curTime = TimeUtils.getCurTime();
        long ban_time = curTime - Tool.HOUR;
        sqlParams.add(ban_time);
        sqlParams.add(curTime);
        sqlParams.add(type);
        long thinkingUserId = 0;
        switch (type) {
            case 0:
                //封角色
                String uid = params.getString("uid");// 用户ID
                long userId = Long.parseLong(uid);
                UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
                userExtInfo.putBannedTime(ban_time);
                userExtInfo.updateQueueNow();
                whereSql += " and user_id = ?";
                sqlParams.add(userId);
                thinkingUserId = userId;
                break;
            case 1:
                //封账号
                String accountId = params.getString("account_id");
                int platform = params.getInteger("platform");
                whereSql += " and account_id = ? " + " and platform = ? " ;
                sqlParams.add(accountId);
                sqlParams.add(platform);
                break;
            case 2:
                //封设备
                String devoceId = params.getString("device_id");
                whereSql += " and device_id = ?" ;
                sqlParams.add(devoceId);
                break;
            case 3:
                //封ip
                String ip = params.getString("ip");
                whereSql += " and ip = ? " ;
                sqlParams.add(ip);
                break;
            default:
                break;

        }

        //解封 封号结束时间设置为过去一小时，操作时间更新当前
        String updateSql = "UPDATE banned_user SET ban_time = ? , add_time = ? WHERE " + whereSql ;
        MysqlTool.updateToDb(MysqlClient.getServerPool(), updateSql, sqlParams, handler -> {
            if (handler.failed()) {
                logger.error("handleUnSeal sql fail params = " + params + " error:" + handler.cause());
            }
        });
        if (thinkingUserId > 0) {
            // 数数用户封禁事件
//            ThinkingDataManager.pushUserBanData(thinkingUserId, 2);
        }
        JsonObject result = new JsonObject();
        result.put("isSqlDel", false);
        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    // 设置玩家等级和vip,声望
    private static void setUserLevelVip(UserInfo userInfo, long userId, int level, byte vip, int repu) {
        userInfo.putLevel(level);
        userInfo.putVip(vip);
        userInfo.putRepu(repu);
        userInfo.update();

        UserBuild userBuild = BuildManager.getUserBuild(userId, BuildConstant.BUILD_ID_CITY_CENTER);
        if (userBuild != null) {
            userBuild.putLevel(level);
            userBuild.update();
        }
        
        logger.info("###setUserLevelVip finish userid = " + userId + " level:" + level + " vip:" + vip + " repu:" + repu);
    }

    //  设置关卡进度，设置解锁区域
    private static void setUserStage(UserInfo userInfo, long userId, int mapId, int areaId) {
        UserStage userStage = FightManager.getUserStage(userId);
        userStage.putMapId(mapId);
        userStage.putStageId(1);
        userStage.putUnlockAreaId(areaId);
        userStage.putGuardRewardTime(TimeUtils.getCurTime());
        userStage.putGuardRewardRandomTime(TimeUtils.getCurTime());
        userStage.putGuardRewardLastTime(TimeUtils.getCurTime());
        userStage.update();
        logger.info("###setUserStage finish userid = " + userId + " mapId:" + mapId + " areaId:" + areaId);
    }

    // 设置引导已完成
    private static void setUserTeach(UserInfo userInfo, long userId) {
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        userExtInfo.putTeachId(7000);
        userExtInfo.update();
        logger.info("###setUserTeach finish userid = " + userId);
    }

    // 设置人口数量
    private static void setUserCityInfo(UserInfo userInfo, long userId, int peasonNum) {
        PBUserData.Builder pbUserData = PBUserData.newBuilder();
        UserCityInfo userCityInfo = BuildManager.getUserCityInfo(userId);
        userCityInfo.addPeasonMax(pbUserData, userInfo, 100);
        userCityInfo.addPeasonNum(pbUserData, userInfo, 100, LogType.GM_SEND);
        userCityInfo.update();
        logger.info("###setUserCityInfo finish userid = " + userId + " peasonNum:" + peasonNum);
    }

    // 获得所有干员，等级设置为50级
    private static void setUserPartner(UserInfo userInfo, long userId, int level, int maxLevel) {
        for (PartnerMain partnerMain : PartnerManager.getPartnerMainMap().values()) {
            RewardManager.addReward(userInfo, partnerMain.getPartnerId(), 1, null, LogType.GM_SEND);
        }
        for (UserPartner userPartner : PartnerManager.getUserPartnerList(userId)) {
            userPartner.putLevel(level);
            userPartner.putMaxLevel(maxLevel);
            userPartner.update();
        }
        logger.info("###setUserPartner finish userid = " + userId + " level:" + level);
    }

    // 获得所有秘书
    private static void setUserSecr(UserInfo userInfo, long userId) {
        for (SecretaryMain secretaryMain : SecretaryManager.getSecretaryMainMap().values()) {
            RewardManager.addReward(userInfo, secretaryMain.getSecretaryId(), 1, null, LogType.GM_SEND);
        }
        logger.info("###setUserSecr finish userid = " + userId);
    }

    // 获得所有武器，等级设置为50级
    private static void setUserWeapon(UserInfo userInfo, long userId, int level) {
        for (WeaponMain weaponMain : PartnerManager.getWeaponMainMap().values()) {
            RewardManager.addReward(userInfo, weaponMain.getWeaponId(), 1, null, LogType.GM_SEND);
        }
        for (UserWeapon userWeapon : PartnerManager.getUserWeaonList(userId)) {
            userWeapon.putLevel(level);
            userWeapon.update();
        }
        logger.info("###setUserWeapon finish userid = " + userId + " level:" + level);
    }

    // 给初级账号，中级账号，高级账号，添加道具
    private static void setUserItem(UserInfo userInfo, long userId) {
        for (ReviewItem reviewItem : BagManager.getReviewItemMap().values()) {
            RewardManager.addReward(userInfo, reviewItem.getItemId(), reviewItem.getItemNum(), null, LogType.GM_SEND);
        }
        logger.info("###setUserItem finish userid = " + userId);
    }

    /**
     * 发送邮件
     * @param adminName
     * @param reason
     * @param params
     * @param cmd
     * @return
     */
    private static JsonObject handleSendMail(String adminName, String reason, JsonObject params, String cmd) {
        if (!params.containsKey("userids") || !params.containsKey("logtype") || !params.containsKey("item")) {

            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        JsonArray ids = params.getJsonArray("userids");
        int titleId = params.getInteger("titleId");
        int contentId = params.getInteger("contentId");
        int logType = params.getInteger("logtype");
        String item = params.getString("item");
        String contentReplace = params.containsKey("contentReplace") ? params.getString("contentReplace") : "";
        List<RewardItem> list = MailManager.takeRewardItem(item);
        logger.info("handleSendMail titleId = " + titleId + " contentId = " + contentId + " logType = " + logType + " item:" + item);
        logger.info("handleSendMail ids:" + ids.toString());
        for (int i = 0; i < ids.size(); i++) {
            long userId = ids.getLong(i);
            MailManager.sendSystemMailReplaceContent(userId, titleId, contentId,list,logType,contentReplace);
            if (!item.isEmpty()) {
                addWebGmLog(userId, adminName, reason, "send mail items:" + item);
            }
        }
        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    /**
     * 禁言
     */
    private static JsonObject handleBannedChat(String adminName, String reason, JsonObject params, String cmd) {
        if (!params.containsKey("uid") || !params.containsKey("time")) {
            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        String uid = params.getString("uid");// 用户ID
        long userId = Long.parseLong(uid);
        int time = params.getInteger("time");// 禁言结束时间
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (userExtInfo == null) {
            return sendResponse(cmd, ErrorWord.ENTITY_NOT_EXIST);
        }
        userExtInfo.putSealTime(time);
        userExtInfo.updateQueueNow();
        addWebGmLog(userId, adminName, reason, "banned chat time:" + TimeUtils.getTimeStr(time));
//		// 返回客户端数据
        return sendResponse(cmd, ErrorWord.SUCCESS);
    }

    /**
     * 玩家改名
     */
    private static JsonObject handleChangeName(String adminName, String reason, JsonObject params, String cmd) {
        if (!params.containsKey("uid")) {
            return sendResponse(cmd, ErrorWord.BAD_PARAM);
        }
        String uid = params.getString("uid"); // 用户ID
        long userId = Long.parseLong(uid);
        String roleName = "";
        boolean isReset = params.containsKey("isReset") ? params.getBoolean("isReset") : false;
        UserInfo userInfo = GameUser.getUserInfo(userId);
        UserExtInfo userExtInfo = GameUser.getUserExtInfo(userId);
        if (!isReset) {
            if (!params.containsKey("name")) {
                return sendResponse(cmd, ErrorWord.BAD_PARAM);
            }
            roleName = params.getString("name"); // 新名称
            // 检测名称 包括表情符
            ErrorWord errorWord = SensitivewordEngine.checkUserName(roleName, 4, 14,
                    AllParam.OPEN_NAME_SPACE_CHAR == 0);
            if (errorWord != ErrorWord.SUCCESS) {
                return sendResponse(cmd, errorWord);
            }
            // 检测敏感字
            String tempName = roleName;
            try {
                roleName = SensitivewordEngine.replaceNameBySdk(roleName, userExtInfo.getPlatform());
            } catch (Exception e) {
                return sendResponse(cmd, ErrorWord.BAD_WORD);
            }
            if (!tempName.equals(roleName)) {
                return sendResponse(cmd, ErrorWord.BAD_WORD);
            }

            boolean hasEngChar = Tool.checkEngChar(roleName);
            String sql1 = "";
            if (hasEngChar) {
                sql1 = "SELECT 1 FROM user_info WHERE lower(user_name) = lower(?) AND server_id = ? LIMIT 1;";
            } else {
                sql1 = "SELECT 1 from user_info WHERE user_name = ? AND server_id = ? LIMIT 1;";
            }
            JsonArray params1 = new JsonArray();
            params1.add(roleName);
            params1.add(userInfo.getServerId());
            String sql = sql1;
            JsonObject jsonObject = Sync.awaitResult(h ->
                    MysqlTool.queryJsonObjectFromDb(MysqlClient.getGamePool(), sql, params1, h));
            if (jsonObject != null && !jsonObject.isEmpty()) {
                return sendResponse(cmd, ErrorWord.WRONG_STATUS);//名字已经被用了
            }
        } else {
            String s = UUID.randomUUID().toString();
            roleName = s.substring(0, 8) + s.substring(9, 13);   //新的随机昵称
        }
        userInfo.putUserName(roleName);
        userInfo.updateQueueNow();// 名字修改需要立即更新数据库

        //数数SDK记录修改昵称
//        ThinkingDataManager.pushUserChangeNameData(userId, userExtInfo.getDistinctId(), userInfo.getUserName());
//        if (AllParam.SEND_WORD_MONITOR == 1) {
//            JsonObject gobj = GameUser.getGateObj(userId);
//            KafkaBiManager.addWordMonitorLog(userExtInfo.getAccountId(), userExtInfo.getDeviceId(), userId, gobj,
//                    NewbiRequestInfo.MONITOR_TYPE_ROLE_NAME, roleName);
//        }
        addWebGmLog(userId, adminName, reason, "change new name:" + roleName);
//		// 返回客户端数据
        return sendResponse(cmd, ErrorWord.SUCCESS);
    }
}
